package com.wyp.didishige.activity;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.wyp.didishige.MyMessageReceiver;
import com.wyp.didishige.model.Rating;
import com.wyp.didishige.model.Request;
import com.wyp.didishige.utils.IntentUtil;
import com.wyp.didishige.R;
import com.wyp.didishige.model.User;
import com.wyp.didishige.utils.ImageLoadOptions;

import java.util.List;

import cn.bmob.im.bean.BmobInvitation;
import cn.bmob.im.bean.BmobMsg;
import cn.bmob.im.config.BmobConfig;
import cn.bmob.im.inteface.EventListener;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;

public class MessageActivity extends BaseActivity implements EventListener {
    TextView message_title, shiMei_nick;
    ImageView shiMei_head_image;
    Button button_accept;
    BmobMsg msg;
    Request mRrequest;
    public static final int NEW_MESSAGE = 0x001;// 收到消息

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message);

        actionBar = getSupportActionBar();
//        actionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.actionbar));
        actionBar.setDisplayHomeAsUpEnabled(true);
        Bundle bundle = getIntent().getExtras();

        msg = (BmobMsg) bundle.getSerializable("BmobMsg");

        message_title = (TextView) findViewById(R.id.message_title);
        shiMei_nick = (TextView) findViewById(R.id.shiMei_nick);
        button_accept = (Button) findViewById(R.id.button_accept);

        shiMei_head_image = (ImageView) findViewById(R.id.shiMei_head_image);


        shiMei_head_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (msg == null) return;

            }
        });

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        MyMessageReceiver.ehList.add(this);// 监听推送的消息
    }

    @Override
    public void onResume() {
        super.onResume();
        initAccept();

        initData(msg);
//        MyMessageReceiver.ehList.add(this);// 监听推送的消息
//        // 有可能锁屏期间，在聊天界面出现通知栏，这时候需要清除通知和清空未读消息数
//        BmobNotifyManager.getInstance(this).cancelNotify();
//        //清空消息未读数-这个要在刷新之后
//        MyMessageReceiver.mNewNum = 0;
    }

    private void initAccept() {
        BmobQuery<Request> queryRequest = new BmobQuery<>();
        queryRequest.addWhereEqualTo("objectId", msg.getExtra());
        queryRequest.order("-createdAt");
        queryRequest.findObjects(this, new FindListener<Request>() {
            @Override
            public void onSuccess(List<Request> requests) {
                if (requests != null && requests.size() != 0) {
                    mRrequest = requests.get(0);
                    if (mRrequest.isAccept()) {
                        button_accept.setEnabled(false);
                        button_accept.setText("已被抢");
                    } else {
                        button_accept.setText("抢");
                        button_accept.setEnabled(true);
                    }

                    button_accept.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (mRrequest != null && !mRrequest.isAccept()) {
                                isAccept();
                            }
                        }
                    });
                }
            }

            @Override
            public void onError(int i, String s) {
                ShowToast("抢单失败，请重试");
            }
        });
    }

    private void isAccept() {
        BmobQuery<Request> queryRequest = new BmobQuery<>();
        queryRequest.addWhereEqualTo("objectId", msg.getExtra());
        queryRequest.order("-createdAt");
        queryRequest.findObjects(this, new FindListener<Request>() {
            @Override
            public void onSuccess(List<Request> requests) {
                if (requests != null && requests.size() != 0) {
                    mRrequest = requests.get(0);
                    if (mRrequest.isAccept()) {
                        button_accept.setEnabled(false);
                        button_accept.setText("已被抢");
                    } else {
                        refreshRequest();
                    }
                }
            }

            @Override
            public void onError(int i, String s) {
                ShowToast("抢单失败，请重试");
            }
        });
    }

    private void refreshRequest() {
        mRrequest.setAccept(true);
        mRrequest.setShiGeObject(userManager.getCurrentUser(User.class));
        mRrequest.setShiGe(userManager.getCurrentUserName());
        mRrequest.setShiGeNick(userManager.getCurrentUser().getNick());
        mRrequest.update(MessageActivity.this, new UpdateListener() {
            @Override
            public void onSuccess() {
                button_accept.setText("到手");
                button_accept.setEnabled(false);
                setRating();
                gotoChat(msg);
            }

            @Override
            public void onFailure(int i, String s) {
                ShowToast("抢单失败，请重试");
            }
        });
    }

    /**
     * 接单成功后更新或新建评价数据
     */
    private void setRating() {
        BmobQuery<Rating> query = new BmobQuery<>();
        query.addWhereEqualTo("username", userManager.getCurrentUserName());
        query.findObjects(this, new FindListener<Rating>() {
            @Override
            public void onSuccess(List<Rating> ratings) {
                Rating rating;
                if (ratings != null && ratings.size() != 0) {
                    rating = ratings.get(0);
                    rating.setServiceNum(rating.getServiceNum() + 1);
                    rating.update(MessageActivity.this);
                } else {
                    rating = new Rating();
                    rating.setUsername(userManager.getCurrentUserName());
                    rating.setServiceNum(1);
                    rating.save(MessageActivity.this);
                }
            }

            @Override
            public void onError(int i, String s) {

            }
        });
    }

    private void gotoChat(final BmobMsg bmobMsg) {
        BmobQuery<User> query = new BmobQuery<>();
        query.addWhereEqualTo("username", bmobMsg.getBelongUsername());
        query.findObjects(this, new FindListener<User>() {
            @Override
            public void onSuccess(List<User> users) {
                if (users != null && users.size() != 0) {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("user", users.get(0));
                    IntentUtil.start_activity(MessageActivity.this, ChatActivity.class, bundle);
                    ShowToast("你已成功抢单，详细咨询一下吧");
                    BmobMsg mMsg = BmobMsg.createTextSendMsg(MessageActivity.this, bmobMsg.getBelongId(), "我抢到你的单子咯");
                    manager.sendTextMessage(users.get(0), mMsg);
                }
            }

            @Override
            public void onError(int i, String s) {
                ShowToast(s);
            }
        });
    }

    private void initData(BmobMsg msg) {
        if (msg != null) {
            ImageLoader.getInstance().displayImage(msg.getBelongAvatar(), shiMei_head_image, ImageLoadOptions.getOptions());
            shiMei_nick.setText(msg.getBelongNick());
            message_title.setText(msg.getContent());
            button_accept.setClickable(false);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        hideSoftInputView();
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        public void handleMessage(Message message) {
            if (message.what == NEW_MESSAGE) {
                msg = (BmobMsg) message.obj;
                initData(msg);
            }
        }
    };

    @Override
    public void onMessage(BmobMsg message) {
        Message handlerMsg = handler.obtainMessage(NEW_MESSAGE);
        handlerMsg.obj = message;
        handler.sendMessage(handlerMsg);
    }

    @Override
    public void onNetChange(boolean isNetConnected) {
        if (!isNetConnected) {
            ShowToast(R.string.network_tips);
        }
    }

    @Override
    public void onAddUser(BmobInvitation invite) {

    }

    @Override
    public void onOffline() {
    }

    @Override
    public void onReaded(String conversionId, String msgTime) {
        if (msg.getConversationId().equals(conversionId)
                && msg.getMsgTime().equals(msgTime)) {
            msg.setStatus(BmobConfig.STATUS_SEND_RECEIVERED);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == android.R.id.home) {
            finish();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
